// 初始状态
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, { accessedRoutes, constantRoutes }) => {
    state.addRoutes = accessedRoutes
    // 合并constantRoutes和accessedRoutes
    state.routes = [...constantRoutes, ...accessedRoutes]
  }
}

const actions = {
  /**
   * 根据用户角色生成可访问的路由
   */
  generateRoutes({ commit }, { roles, routes, constantRoutes }) {
    return new Promise(resolve => {
      let accessedRoutes
      
      // 如果是管理员，可以访问所有路由
      if (roles.includes('admin')) {
        accessedRoutes = routes || []
      } else {
        // 否则根据角色过滤路由
        accessedRoutes = filterAsyncRoutes(routes, roles)
      }
      
      commit('SET_ROUTES', { accessedRoutes, constantRoutes })
      resolve(accessedRoutes)
    })
  }
}

// 根据用户角色过滤路由
function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

// 判断用户是否有权限访问该路由
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 